package com.wlyuan.open.domain.source.service.impl;

import com.alibaba.fastjson.JSON;
import com.wlyuan.core.exception.AssertUtils;
import com.wlyuan.open.domain.source.assembler.OrderAssembler;
import com.wlyuan.open.domain.source.service.IOpenOrderService;
import com.wlyuan.open.dto.OpenOrderSyncDTO;
import com.wlyuan.open.infrastructure.exception.SourceValueErrorException;
import com.wlyuan.order.api.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;

/**
 * @author yuanzheng
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OpenOrderServiceImpl implements IOpenOrderService {
    @DubboReference(check = false, timeout = 5000, retries = 0)
    private final IOrderService orderService;

    @Override
    public Long sync(OpenOrderSyncDTO source) {
        if (CollectionUtils.isEmpty(source.getGoodsList())) {
            source.setGoodsList(Collections.emptyList());
        }
        if (CollectionUtils.isEmpty(source.getAttachments())) {
            source.setAttachments(Collections.emptyList());
        }
        if (CollectionUtils.isEmpty(source.getTransports())) {
            source.setTransports(Collections.emptyList());
        }
        var creation = OrderAssembler.assembler(source);
        logger.info("请求创建订单：{},{}", source.getSourceKey(), JSON.toJSON(creation));
        var order = orderService.rewrite(creation);
        AssertUtils.assertNotNull(order, new SourceValueErrorException("创建订单失败"), source);
        return order.getOrderId();
    }
}
